import { contextBridge, ipcRenderer } from 'electron'
// import { electronAPI } from '@electron-toolkit/preload'
let mediaRecorder = null
// Custom APIs for renderer
const api = {
    // mediaRecorder: null,
    getMedia: async (n) => {
        let sources = await ipcRenderer.invoke('get_media', n)
        return sources
    },
    // returnStream: async (sourceId) => {
    //     const stream = await navigator.mediaDevices.getUserMedia({
    //         audio: false,
    //         video: {
    //             mandatory: {
    //                 chromeMediaSource: 'desktop',
    //                 chromeMediaSourceId: sourceId,
    //                 minWidth: 1280,
    //                 maxWidth: 1280,
    //                 minHeight: 720,
    //                 maxHeight: 720
    //             }
    //         }
    //     })
    //     return stream
    // },
    // getStream: (sourceId) => ipcRenderer.invoke('get_stream', sourceId)
    getStream: async (sourceId) => {
        try {
            let stream = await navigator.mediaDevices.getUserMedia({
                audio: false,
                video: {
                    mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: sourceId,
                        minWidth: 1280,
                        maxWidth: 1280,
                        minHeight: 720,
                        maxHeight: 720
                    }
                }
            })
            const video = document.querySelector('#video1')
            video.srcObject = stream
            video.onloadedmetadata = (e) => video.play()
            let chunks = [];
            mediaRecorder = new MediaRecorder(stream);
            mediaRecorder.onstart = () => {
                mediaRecorder.ondataavailable = function (e) {
                    chunks.push(e.data);
                }
            };

            mediaRecorder.ondataavailable = function (e) {
                chunks.push(e.data);
            }

            mediaRecorder.onstop = async (e) => {
                let recorderFile = new Blob(chunks, {
                    'type': 'video/webm'
                });
                chunks = [];
                let dateTime = new Date().getTime()
                // var file = new File([recorderFile], 'video-' + dateTime + '.mp4', {
                //   type: 'video/mp4'
                // })
                const elink = document.createElement('a')
                elink.style.display = 'none'
                elink.download = dateTime + '.webm'
                elink.href = URL.createObjectURL(recorderFile)
                document.body.appendChild(elink)

                elink.click()
                URL.revokeObjectURL(elink.href)
                document.body.removeChild(elink)
                mediaRecorder = null
                stream = null
                video.pause()
                video.srcObject = null
            };

        } catch (e) {
            console.log(e)
        }

    },
    stop: () => {
        console.log('触发停止');
        if (mediaRecorder) { mediaRecorder.stop() }
    },
    start: () => {
        if (mediaRecorder) { mediaRecorder.start() }
    },

    setStop: (n) => {
        ipcRenderer.on('set_stop', n)


    },
    setStart: (n) => {

        ipcRenderer.on('set_start', n)

    },
    minSize: () => {
        ipcRenderer.send('min_size')
    },
    closeWin: () => {
        ipcRenderer.send('close_win')
    }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
    try {
        // contextBridge.exposeInMainWorld('electron', electronAPI)
        contextBridge.exposeInMainWorld('api', api)
    } catch (error) {
        console.error(error)
    }
} else {
    // window.electron = electronAPI
    window.api = api
}
